import MenuData from './datas/menu/menu.json'
import tool from '@/utils/tools.js'
export default {
    namespaced: true,
    state: {
        menus: MenuData,
        currentMenuIndex: 0,
        cart: uni.getStorageSync('cart') || [],
        showCart: false
    },
    mutations: {
        SET_CURRENT_MENU_INDEX (state, index) {
            state.currentMenuIndex = index
        },
        SET_CART (state, cart) {
            state.cart = cart
            uni.setStorageSync('cart', cart)
        },
        SET_SHOW_CART (state, showCart) {
            state.showCart = showCart
        }
    },
    getters: {
        cartTotalPrice (state) {
            const price = state.cart.reduce(
                (total, item) => total + item.productPrice * item.quantity, 0
            )
            return tool.formatPrice(price * 100)
        },
        cartTotalQuantity (state) {
            return state.cart.reduce((total, item) => total + item.quantity, 0)
        }
    },
    actions: {
        setCurrentMenuIndex ({ commit }, index) {
            commit('SET_CURRENT_MENU_INDEX', index)
        },
        addToCart ({ commit, state }, product) {
            const findIndex = state.cart.findIndex(
                item => item.productId == product.productId &&
                    item.attrAndSpecText == product.attrAndSpecText
            )
            if (findIndex !== -1) {
                state.cart[findIndex].quantity += product.quantity
                commit('SET_CART', [...state.cart])
            } else {
                commit('SET_CART', [...state.cart, product])
            }
        },
        minusQuantity ({ commit, state }, index) {
            if (state.cart[index].quantity <= 1) {
                state.cart.splice(index, 1)
            } else {
                state.cart[index].quantity -= 1
            }
            commit('SET_CART', [...state.cart])
            if (state.cart.length == 0) {
                commit('SET_SHOW_CART', false)
            }
        },
        addQuantity ({ commit, state }, index) {
            state.cart[index].quantity += 1
            commit('SET_CART', [...state.cart])
        },
        clearCart ({ commit }) {
            commit('SET_CART', [])
        }
    }
}